<?php

namespace App\Http\Repositories\StoreCenter;

use App\Http\Repositories\BaseRepository;
use App\Models\StoreCenter\Models\OrderModel;

class OrderRepository extends BaseRepository
{
    public $order;
    public function __construct(OrderModel $order)
    {
        $this->order = $order;
    }

    public function getOrderInfo($data)
    {
        if (isset($data['id'])) {
            $where['id'] = $data['id'];
        } else {
            $where['order_code'] = $data['order_code'];
        }

        return $this->order->getOrderInfo($where);
    }

    public function getOrderList($data)
    {
        return $this->order->getOrderList($data);

    }

    public function addOrder($data)
    {
        $data['order_code'] = getCode();
        $order = $this->order->addItem($data, true);

        foreach ($data['sku_info'] as $v) {
            $order->skuInfo()->create($v);
        }

        return [];
    }

    public function editOrder($data)
    {
        $where['id'] = $data['id'];

        $update['status'] = $data['status'];

        $this->order->editItem($where, $update);

        return [];
    }

    public function delOrder($data)
    {
        $success = 0;
        $fail = 0;
        $message = '';

        $ids = explode(',', $data['ids']);
        foreach ($ids as $k => $v) {
            $order = $this->order->find($v);
            if (is_null($order)) {
                $fail ++;
                $message .= '第'.($k+1).'个删除失败的原因:数据不存在;';
            } elseif ($order->status != OrderModel::STATUS_WAITING
                || $this->order->getCurrentUserId() == $order->create_user_uuid) {
                $fail ++;
                $message .= '第'.($k+1).'个删除失败的原因:非法操作;';
            } else {
                $success ++;
                $order->delete();
            }
        }
        return ['message' => '成功删除'.$success.'个;失败'.$fail.'个;'.$message];

    }


}

